package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.MarketActivityUserEntity;
import com.xbongbong.saas.domain.entity.ext.MarketActivityEntityExt;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.MarketActivityEnum;
import com.xbongbong.saas.help.workflow.MarketActivityForStaticHelp;
import com.xbongbong.saas.model.MarketActivityModel;
import com.xbongbong.saas.model.MarketActivityUserModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.service.ConsistencySyncService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import org.elasticsearch.action.support.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
public class WorkflowMarketActivityStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    private static Logger log = LoggerFactory.getLogger(WorkflowMarketActivityStrategy.class);


    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private MarketActivityForStaticHelp marketActivityForStaticHelp;
    @Resource
    private MarketActivityModel marketActivityModel;
    @Resource
    private MarketActivityUserModel marketActivityUserModel;
    @Resource
    private ConsistencySyncService consistencySyncService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.MARKET_ACTIVITY.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        Data pojoData = workflowTransferPOJO.getData();

        MarketActivityEntityExt marketActivityEntityExt = marketActivityModel.getByKey(pojoData.getId(), workflowTransferPOJO.getCorpid());


        marketActivityForStaticHelp.addMarketActivity(marketActivityEntityExt, XbbRefTypeEnum.MARKET_ACTIVITY);
        addLinkDataDynamic(workflowTransferPOJO);
        // api
        apiHook(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        Long dataId = pojoData.getId();


        MarketActivityEntityExt marketActivityEntityExt = marketActivityModel.getByKey(dataId, workflowTransferPOJO.getCorpid());
        marketActivityForStaticHelp.updateMarketActivity(marketActivityEntityExt, RedundantTemplateTypeEnum.MARKET_ACTIVITY);


        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);

        // 数据一致性同步
        try{
            String oldName = FastJsonHelper.getStringOrDefaultFromFormData(workflowBackupDataEntity.getData(), MarketActivityEnum.NAME.getAttr(), "");
            String opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(pojoData.getData(), MarketActivityEnum.NAME.getAttr(), "");
            if (!Objects.equals(oldName, opObjectName)) {
                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(corpid, dataId, opObjectName);
                consistencySyncService.syncMarketActivity(consistencySyncRabbitMqDTO);
            }
        }catch (Exception e){
            log.error("数据一致性同步", e);
        }
        // 更新市场活动
        marketActivityForStaticHelp.updateMarketActivity(marketActivityEntityExt, RedundantTemplateTypeEnum.MARKET_ACTIVITY);
        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException{
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Long backupDataId = workflowTransferPOJO.getBackupDataId();
            Long dataId = workflowTransferPOJO.getData().getId();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                MarketActivityEntityExt marketActivityEntityExt = new MarketActivityEntityExt();
                marketActivityEntityExt.setId(dataId);
                marketActivityEntityExt.setCorpid(corpid);
                marketActivityEntityExt.setData(data);
                marketActivityEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                // 获取负责人
                marketActivityEntityExt.setOwnerId(getOwnerId(data));
                marketActivityEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
                List<MarketActivityUserEntity> contractUserList = JSON.parseArray(data.getString(StringConstant.USER_TEAM), MarketActivityUserEntity.class);

                FormDataUtil.removeSystemData(data);
                data.remove(StringConstant.USER_TEAM);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    marketActivityEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                marketActivityModel.update(marketActivityEntityExt);
                // 回退被删掉的子表单
                updateBackSubForm(marketActivityEntityExt, corpid, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_SUB);
                //回退被删掉的富文本
                updateBackRichText(taskId, workflowTransferPOJO);
                saveUserTeam(contractUserList, corpid, marketActivityEntityExt.getId());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowMarketActivityStrategy.updateBack error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            MarketActivityEntityExt marketActivityEntityExt = new MarketActivityEntityExt();
            marketActivityEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                marketActivityEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                marketActivityEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            marketActivityEntityExt.setCorpid(corpid);
            marketActivityEntityExt.setUpdateTime(DateTimeUtil.getInt());
            marketActivityModel.update(marketActivityEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            // 团队
            List<MarketActivityUserEntity> contractUserList = marketActivityUserModel.getMarketActivityUserList(corpid, dataId, null);
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                marketActivityUserModel.deleteBatch(corpid, contractUserList, WriteRequest.RefreshPolicy.NONE, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowMarketActivityStrategy.approvalFailed error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 保存团队
     * @param list
     * @param corpid
     * @param dataId
     * @throws XbbException
     */
    private void saveUserTeam(List<MarketActivityUserEntity> list, String corpid, Long dataId) throws XbbException {

        try {
            List<MarketActivityUserEntity> contractUserList = marketActivityUserModel.getMarketActivityUserList(corpid, dataId, null);
            List<Long> idList = new ArrayList<>();
            list.forEach(item->idList.add(item.getId()));

            contractUserList.removeIf(item->idList.contains(item.getId()));
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                marketActivityUserModel.deleteBatch(corpid,contractUserList, WriteRequest.RefreshPolicy.NONE, DelEnum.DELETE.getDel());
            }
            if (CollectionsUtil.isNotEmpty(list)) {
                marketActivityUserModel.updateBatch(list, corpid);
            }


        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowMarketActivityStrategy.saveUserTeam error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
